package com.sjf.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sjf.common.BaseContext;
import com.sjf.common.CustomException;
import com.sjf.reggie.entity.*;
import com.sjf.reggie.mapper.OrdersMapper;
import com.sjf.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author <huangtang>
 * @since 2022/4/27 17:01
 **/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    OrderDetailService detailService;
    @Autowired
    OrdersService ordersService;

    @Autowired 
    UserService userService;
    @Autowired
    AddressBookService addressBookService;

    @Override
    @Transactional
    public void submit ( Orders orders ) {
        //获取用户Id
        Long userId = BaseContext.getCurrentId ();
        orders.setUserId (userId);
        //查询购物车数据
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<> ();
        wrapper.lambda ().eq ( ShoppingCart::getUserId, userId );
        List<ShoppingCart> shoppingCarts = shoppingCartService.list ( wrapper );
        if(shoppingCarts == null){
            throw new CustomException ("购物车为空，不能下单！");
        }
        long orderId = IdWorker.getId ();
        //计算购物车总价
        //原子性操作，保证线程安全
        AtomicInteger amount = new AtomicInteger (0);
        List<OrderDetail> orderDetails = shoppingCarts.stream ().map (( item)->{
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId (orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount (item.getAmount ());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //查询用户数据
        User user = userService.getById (userId);
        //查询地址信息
        AddressBook addressBook = addressBookService.getById (orders.getAddressBookId ());
        if(addressBook == null){
            throw new CustomException ("地址信息不存在！");
        }
        orders.setNumber (orderId + "");
        orders.setOrderTime (LocalDateTime.now ());
        orders.setCheckoutTime (LocalDateTime.now ());
        orders.setStatus (2);
        orders.setAmount (new BigDecimal (amount.get ()));
        orders.setConsignee (addressBook.getConsignee ());
        orders.setPhone (addressBook.getPhone ());
        orders.setUserName (user.getName ());
        //插入订单表数据
        ordersService.save ( orders );
        //插入订单明细表数据
        detailService.saveBatch (orderDetails);
        //下单完成后，清除购物车数据
        shoppingCartService.remove (wrapper);
    }

    @Override
    public Page getList ( Integer page , Integer pageSize ) {
        Page pageInfo = new Page (page , pageSize);

        QueryWrapper<Orders> wrapper = new QueryWrapper<> ();
        wrapper.lambda ().orderByDesc (Orders::getOrderTime);
        return ordersService.page (pageInfo , wrapper);
    }
}
